package com.gen.generator.service;

import com.gen.generator.config.CodeGenConfig;
import com.gen.generator.util.DBUtil;
import com.gen.generator.util.VelocityUtil;

import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class CodeGenerator {
    private final static Set<String> superColumns = new HashSet<>(Arrays.asList(
            "id", "createBy", "createTime", "updateBy", "updateTime", "delFlag", "remark", "tenantId", "version"
    ));

    public static void generate(CodeGenConfig config) throws Exception {
        // 获取表结构
        List<Map<String, Object>> columns = DBUtil.getTableColumns(config);
        config.setColumns(columns);
        genCode(config);
    }

    public static void genCode(CodeGenConfig config) throws Exception {
        Map<String, Object> data = new HashMap<>();
        String tableName = config.getTableName();
        String packageName = config.getPackageName();
        String author = config.getAuthor();
        List<Map<String, String>> templates = config.getTemplates();
        Boolean tenant = config.getTenant();
        String outputDir = config.getOutputDir();
        List<Map<String, Object>> columns = config.getColumns();
        Set<String> importList = new HashSet<>();
        columns.forEach(column -> {
            String javaType = (String) column.get("javaType");
            if ("LocalDateTime".equals(javaType)) {
                importList.add("java.time.LocalDateTime");
            }else if ("BigDecimal".equals(javaType)){
                importList.add("java.math.BigDecimal");
            }
        });

        String camelCase = DBUtil.toCamelCase(tableName);
        String capitalize = DBUtil.capitalize(camelCase);
        data.put("tableName", tableName);
        data.put("functionName", capitalize + " 管理");
        data.put("columns", columns);
        data.put("packageName", packageName);
        data.put("ClassName", capitalize);
        data.put("className", camelCase);
        data.put("author", author);
        data.put("datetime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        Map<String, Object> tableMap = new HashMap<>();
        tableMap.put("crud", true);
        tableMap.put("sub", true);
        tableMap.put("tree", false);
        tableMap.put("superColumns", superColumns);
        data.put("table", tableMap);
        data.put("moduleName", camelCase);
        data.put("permissionPrefix", camelCase);
        data.put("pkColumn", DBUtil.pkColumn);
        data.put("IsTenant", tenant?1:0);
        data.put("importList", importList);
        // 遍历模板生成代码
        for (Map<String, String> tpl : templates) {
            String templateFile = "templates/" + tpl.get("name");
            String subPackage = packageName.replace(".", "/") + "/" + tpl.get("subPackage").replace(".", "/");
            String className = capitalize + tpl.get("suffix");
            String fileType = tpl.get("fileType");

            String outputPath = outputDir + "/gen/" + subPackage + "/" + className + fileType;

            File outputFile = new File(outputPath);
            outputFile.getParentFile().mkdirs();
            FileWriter writer = new FileWriter(outputFile, StandardCharsets.UTF_8);

            VelocityUtil.renderToFile(
                    templateFile,
                    writer,
                    data
            );
        }
    }
}
